 // pages/index/Share/ShareHotMoney.js
var app = getApp();
const http = require("../../../utils/util.js");
var Crypto = require('../../../utils/cryptojs/cryptojs.js').Crypto;
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
var playVoiceInterval;
Page({
  data: { 
    userInfo:[], 
    options:[],
    isShowShare:false,  //判断显示的页面， false 为 转发按钮页面，
    isLingqu:false,     //判断红包是不是可以领取，true 为已经领取红包  false可以领取红包；
    windowWidth:'',
    windowHeight:'',
    winnerLength:'',
    winners: [],      //领取红包得所有人得信息
    myWinInfo:[],     //当前领取红包人得金额
    myInfo:[],        //领取红包人得Id
    baseInfo:[],      //发红包人得所有信息 以及红包信息
    totalMoney:0,
    hiddenLoading:true,   //控制 loading 得显示

    count:0,            //红包总个数
    remaincount:0,      //红包剩余个数’
    money:0,            // 红包总金额
    token:'',
    selfwinMoney:'0',   //自己抢到的钱数，

    // 语音播放动画；
    isPlayVoice: false,
    playVoiceUrl:"../../image/playVoice-1.png",
    playVoicepreUrl: '../../image/playVoice-',
    playVoicenextUrl: '.png',

    isPlayVoiceSon:true,
    current:-1,

    avatarurl:'',       //发红包人的头像
    BaseInfoNickName:'',   //发红包人的昵称
    erweima:'../../image/qwe.png',

    isFinished:false,
    ListmpUrl:'',

    jubenAnswer:true,
    QuestionAnswer:"",

    ossMpurl:'',   // 生成红包时的语音，倾听和剧本
    repeat:true,     //限制倾听抢红包重复请求

    advertInfo:[],   //广告链接信息
    content:"",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that  = this;
    console.log(options)
    // 判断是分享链接进入，还是发红包进入
    that.setData({
      options:options,
      QuestionAnswer:options.answer,
    })
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        that.setData({
          windowWidth:res.windowWidth,
          windowHeight:res.windowHeight,
        })
      },
    })
    wx.getUserInfo({
      success:function(res){
        console.log(res.userInfo) 
        that.setData({
          userInfo: res.userInfo,
          avatarurl: res.userInfo.avatarUrl,
        })
      }
    }) 
    wx.getStorage({
      key: 'token',
      success: function(res) {
        that.setData({
          token:res.data,
        })
      },
    })   
    if(options.style==1){
      that.lingHongBao();
    }else{
      that.setData({
        isShowShare:false,
      })
    }

    that.wxxcode();
    // that.redpackInfo();
  },
  wxxcode:function(){
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function(res) {
        var timestamp = app.timestamp();
        var token = res.data;
        var url = app.globalData.localApi +"/redpack/wxxcode";
        wx.request({
          url: url,
          method:"POST",
          data:{
            timestamp:timestamp,
            token:token,
            sign:Crypto.MD5(app.sign(url,token,timestamp)),
            url: app.urlStr(url),
            redpackId: that.data.options.orderno,  
            },
          success: function (res) {
            console.log("二维码")
            console.log(res)
            if(res.data.code==0){
              that.setData({
                erweima: res.data.data.wxxcodeUrl,
              })
            }
          }
        })
      },
    })

  },
    //语音播放动画
  playVoicePlay: function () {
    var that = this;
    var i = 0;
    that.playVoiceInterval = setInterval(function () {
      i++;
      i = i % 4;
      that.setData({
        playVoiceUrl: that.data.playVoicepreUrl + i + that.data.playVoicenextUrl,
      });
    }, 500);
  },
  // 倾听红包播放语音；
  HotplayVoice:function(){
    var that = this;
    that.setData({
      isPlayVoice: true,
    })
        //播放语音动画；
    console.log("执行HotPlayVoice")
    var mpUrl = that.data.ossMpurl;
    console.log("播放MP3")
    console.log(mpUrl)
    

    innerAudioContext.autoplay = true
    innerAudioContext.src = mpUrl,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
        that.playVoicePlay();
      })
    innerAudioContext.onEnded(() => {
      console.log("语音自然播放结束")
      that.setData({
        isPlayVoice: false,
        jubenAnswer:false,
      })
      if (that.data.options.houBaoStyle==2&&that.data.repeat){
        that.getQingting();
      }     
      clearInterval(that.playVoiceInterval);  //清除语音播放动画；
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
      that.setData({
        isPlayVoice: false,
      })
      clearInterval(that.playVoiceInterval);   //清除语音播放动画；
    })
  },

  // 红包列表播放语音
  playVoice:function(e){
    var that = this;
    clearInterval(that.playVoiceInterval); 
    that.setData({
      current:e.currentTarget.dataset.index,
      ListmpUrl: e.currentTarget.dataset.mp,
    })
    var mpUrl = that.data.ListmpUrl;
    console.log("播放口令红包语音") 
    console.log(mpUrl);
    innerAudioContext.autoplay = true
    innerAudioContext.src = mpUrl,
    innerAudioContext.onPlay(() => {
      console.log('开始播放')
      that.playVoicePlay();    //播放语音动画；
    })
    innerAudioContext.onEnded(()=>{
      console.log("语音自然播放结束！")
      that.setData({
        current:-1,
      })
      clearInterval(that.playVoiceInterval);  //清除语音播放动画；
    })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
      that.setData({
        current: -1,
      })
      clearInterval(that.playVoiceInterval);   //清除语音播放动画；
    })

  },
  getQingting:function(){
    var that = this;
    console.log("开始执行getQingting 抢红包");
    that.setData({
      hiddenLoading:false,
    })
    var url = app.globalData.localApi +"/redpack/getQingting";
    var token = that.data.token;
    var timestamp = app.timestamp();
    wx.request({
      url: url,
      method:"POST",
      data:{
        token:token,
        timestamp:timestamp,
        sign:Crypto.MD5(app.sign(url,token,timestamp)),
        orderno:that.data.options.orderno,
        url:app.urlStr(url)
      },
      success:function(res){
        console.log("倾听红包的抢红包成功回调返回的参数")
        that.setData({
          hiddenLoading: true,
          repeat:false,
        })
        console.log(res);
        if (res.data.code == 201) {
          app.login();
        }
        var obj = res.data;
        console.log(obj);
        if (obj.success) {
          that.setData({
            isLingqu: true,
            baseInfo: obj.data.baseInfo,
            winners: obj.data.winners,
            myWinInfo: obj.data.myWinInfo,
            myInfo: obj.data.myInfo,
            totalMoney: parseInt(obj.data.baseInfo) / 100,
            count: obj.data.baseInfo[0].count,
            money:obj.data.baseInfo[0].money,
            remaincount:obj.data.baseInfo[0].remaincount
          })
        } else {
          let str = obj.msg;
          console.log(str);
          if (str == undefined) {
            app.showInfo("抢包失败")
          } else {
            app.showInfo(str);
          }

        } 
      },
      fail:function(res){
        that.setData({
          hiddenLoading: true,
        })
        console.log("倾听红包的抢红包失败回调返回的参数")
        console.log(res);
        app.showInfo("抢包失败，再接再厉")
      }
    })
  },

  // 判断红包状态
  lingHongBao:function(){
    var that = this;
    console.log("调用领红包")
    wx.getStorage({
      key: 'token',
      success: function(res) {
        console.log(res)
        var token = res.data;
        var timestamp = app.timestamp();
        var url = app.globalData.localApi + "/redpack/uploadVoice";
        wx.request({
          url: url,
          method:"POST",
          data:{
            token:token,
            timestamp:timestamp,
            sign: Crypto.MD5(app.sign(url,token,timestamp)),
            orderno:that.data.options.orderno,
            url: app.urlStr(url),
          },
          success:function(res){
            //  1 你已抢过该红包
            //  -3 红包已经抢完 
            //  -2 红包异常；
            // code=0;返回order 更新红包的金额  数量，
            console.log("uploadVoice请求成功")
            console.log(res)
            if(res.data.code==-1){ 
              that.setData({
                isShowShare: true, 
                isLingqu: true,
              })
            }else if(res.data.code==201){
              app.login();
            }else if(res.data.code==0){  
              that.setData({
                isShowShare: true, 
                isLingqu:false,
                count:res.data.order.count,
                money:res.data.order.money,
                remaincount: res.data.order.remaincount, 
                QuestionAnswer:res.data.order.content,
                ossMpurl: res.data.order.ossMp3Url,
                avatarurl: res.data.order.avatarurl,
                BaseInfoNickName:res.data.order.nickname,
                content:res.data.order.content,
                advertInfo:res.data.advertInfo,
              })   
            }else if(res.data.code==1){   
              that.setData({
                isShowShare: true,
                isLingqu: true,
                ossMpurl: res.data.order.ossMp3Url,
                avatarurl: res.data.order.avatarurl,
                advertInfo: res.data.advertInfo,
                content: res.data.order.content,
              })
              that.redpackInfo();
            }else if(res.data.code==-3){  
                that.setData({
                  isShowShare: true,
                  isLingqu: true,
                  isFinished:true,
                  ossMpurl: res.data.order.ossMp3Url,
                  avatarurl: res.data.order.avatarurl,
                  advertInfo: res.data.advertInfo,
                  content: res.data.order.content,
                })
              that.redpackInfo();
            }else {                      
              that.setData({
                isShowShare: false,
              })

            }


          },
          fail:function(res){
            console.log(res)
          }
        })

      },
    })
  },
  // 去体现
  toTixian:function(){
    wx.navigateTo({
      url: '../../tixian/tixian',
    })
  },
  // 再发一个
  toindex:function(){
    wx.navigateTo({
      url: '../houbao/houbao',
    })
  },
  // 去转发 
  toshare:function(){
    var that = this;
    console.log("去转发")
   that.setData({
     isShowShare:false,
   })
  },
  tosharePic:function(){
    var that = this;
    wx.navigateTo({
      url: '../../index/Share/sharePic?orderno='+that.data.options.orderno,
    })
  },

  // 获取语音
  startVoice: function () {
    var that = this;
    console.log("开始录音")
    app.getVoice();
  },
  endstartVoice: function () {
    var that = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log('停止录音', res.tempFilePath)
      that.uploadVoice(res.tempFilePath);
    })
  },
  // 上传语音：
  uploadVoice: function (tempFilePath) {
    var that = this; 
    console.log("程序进入上传语音");
    that.setData({
      hiddenLoading:false,
    })  
    wx.getStorage({
      key: 'token',
      success: function (res) {
        const token = res.data;
        const url = app.globalData.localApi + "/redpack/receiveVoice";
        wx.uploadFile({
          url: url,
          filePath: tempFilePath,
          name: "file",
          formData: {
           token:token,
           redpackId:that.data.options.orderno,
           url: app.urlStr(url),
          },
          header: { "Content-Type": "multipart/form-data" },
          success: function (res) {
            // console.log("抢红包成功")
            that.setData({
              hiddenLoading: true,
            })
            if(res.data.code==201){
              app.login();
            }
            var obj = JSON.parse(res.data);
            console.log(obj);
            if(obj.success){
              that.setData({
                isLingqu: true,
                baseInfo:obj.data.baseInfo,
                winners:obj.data.winners,
                myWinInfo: obj.data.myWinInfo,
                myInfo: obj.data.myInfo,
                totalMoney: parseInt(obj.data.baseInfo)/100,
                count: obj.data.baseInfo[0].count,
                money: obj.data.baseInfo[0].money,
                remaincount: obj.data.baseInfo[0].remaincount
              })
            }else{
              let str = obj.msg;
              console.log(str);
              if(str==undefined){
                app.showInfo("抢包失败")
              }else{
                app.showInfo(str);
              }
              
            } 
          },
          fail: function (res) {
            that.setData({
              hiddenLoading: true,
            })
            console.log(res)
            console.log("上传失败")
            app.showInfo("您读得不够准确，请再接再励")
            that.setData({
              voiceResult: false,
            })
          }
        })
      },
    })
  },
  // 红包得详细信息
  redpackInfo:function(){
    var that  = this;
    console.log("掉起redpackInfo;")
    wx.getStorage({
      key: 'token',
      success: function(res) {
        var token = res.data;
        var timestamp = app.timestamp();
        var url = app.globalData.localApi+"/redpack/info";
        wx.request({
          url: url,
          method:"POST",
          data:{
            token:token,
            timestamp:timestamp,
            sign:Crypto.MD5(app.sign(url,token,timestamp)),
            orderno:that.data.options.orderno,
            url: app.urlStr(url),
          },
          success:function(res){
            console.log(res)
            if(res.data.code==201){
              app.login();
            }else if(res.data.success){
              that.setData({
                winners:res.data.data.winners,
                myWinInfo:res.data.data.myWinInfo[0],
                avatarurl: res.data.data.baseInfo[0].avatarurl,
                BaseInfoNickName: res.data.data.baseInfo[0].nickname,
                count: res.data.data.baseInfo[0].count,
                money: res.data.data.baseInfo[0].money,
                remaincount: res.data.data.baseInfo[0].remaincount,
              })
            }
          },
          fail:function(res){
            console.log(res)
          }
        })
      },
    })
  },
// 收集广告的点击量
  advertClick:function(){
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function(res) {
        var token = res.data;
        var url = app.globalData.localApi+"/advert/click";
        var timestamp = app.timestamp();
        wx.request({
          url: url,
          method:"POST",
          data:{
            token:token,
            timestamp:timestamp,
            sign:Crypto.MD5(app.sign(url,token,timestamp)),
            url:app.urlStr(url),
            orderno:that.data.options.orderno
          },
          success:function(res){
            console.log(res)
          }
        })
      },
    })
  },
  tomyRecord:function(){
    wx.navigateTo({
      url: '../../index/mRecord/myRecord',
    })
  },
  tojubao:function(){
    var that = this;
    wx.navigateTo({
      url: '../../question/jubao',
    })
  },
  toWebView:function(e){
    var that = this;
    var http = e.currentTarget.dataset.url;
    console.log(http);
    that.advertClick();
    wx.navigateTo({
      url: './ifrom?http='+http,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */

    onShareAppMessage: function (res) {
      var that = this;
      console.log("开始执行转发")
      return {
        title: "小程序红包",
        path: "/pages/fuli/shopShare/shopShare?Money=" + that.data.options.Money
        + "&Number=" + that.data.options.Number
        + "&kouling=" + that.data.options.kouling
        + "&houBaoStyle=" + that.data.options.houBaoStyle
        + "&style=1"
        + "&orderno=" + that.data.options.orderno
        + "&mpurl=" + that.data.options.mpUrl,
        success: function (res) {
          app.showInfo("转发成功")
          console.log(res)
          // that.setData({
          //   isShowShare:true
          // })
        },
        fail: function (res) {
          app.showInfo("转发失败")
          console.log(res)
        }

      }
    }
  
})